package com.liner.system.controller;


import com.liner.common.help.JwtHelper;
import com.liner.common.help.MD5;
import com.liner.common.result.Result;
import com.liner.common.result.ResultCodeEnum;
import com.liner.model.system.SysUser;
import com.liner.model.vo.LoginVo;
import com.liner.system.handler.LinAuthException;
import com.liner.system.service.SysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@Api(tags = "用户登录接口")
@RestController
@RequestMapping("/admin/system/index")
public class IndexController {


    @Autowired
    private SysUserService sysUserService;

    @ApiOperation(value = "用户登录")
    @PostMapping("login")
    public Result login(@RequestBody LoginVo loginVo) {
        //根据username查询数据
        SysUser sysUser = sysUserService.getUserInfoByUsername(loginVo.getUsername());

        //用户为空
        if (sysUser == null) {
            throw new LinAuthException(ResultCodeEnum.USER_NOT_FOUND);
        }
        //判断密码是否一致
        String password = loginVo.getPassword();
        String md5Password = MD5.encrypt(password);
        if (!sysUser.getPassword().equals(md5Password)) {
            throw new LinAuthException(ResultCodeEnum.PASSWORD_ERROR);
        }
        //判断用户是否可用
        if (sysUser.getStatus() == 0) {
            throw new LinAuthException(ResultCodeEnum.ACCOUNT_STOP);
        }
        //根据userId和username生成token字符串，返回map
        String token = JwtHelper.createToken(sysUser.getId(), sysUser.getUsername());
        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        return Result.ok(map);
    }

    @ApiOperation(value = "用户信息")
    @GetMapping("info")
    public Result info(HttpServletRequest request) {
        //获取请求头token的字符串
        String token = request.getHeader("token");
        //从token字符串获取用户名称
        String username = JwtHelper.getUsername(token);
        //根据用户名称获取用户信息
        Map<String,Object> map = sysUserService.getUserInfo(username);
        return Result.ok(map);
    }

    @ApiOperation(value = "用户退出")
    @PostMapping("logout")
    public Result logout() {
        return Result.ok();
    }
}
